<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\Radar\Action\Operation;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\Corp\Logic\AppTrait;
use MoChat\App\WorkAgent\Contract\WorkAgentContract;
use MoChat\App\WorkAgent\QueueService\MessageRemind;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkContact\Contract\WorkContactEmployeeContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\AutoTag\Action\Dashboard\Traits\AutoContactTag;
use MoChat\Plugin\Radar\Contract\RadarChannelContract;
use MoChat\Plugin\Radar\Contract\RadarChannelLinkContract;
use MoChat\Plugin\Radar\Contract\RadarContract;
use MoChat\Plugin\Radar\Contract\RadarRecordContract;

/**
 * 互动雷达-H5 PDF、文章阅读回调.
 *
 * Class ReadCallback.
 * @Controller
 */
class ReadCallback extends AbstractAction
{
    use ValidateSceneTrait;
    use AutoContactTag;
    use AppTrait;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @Inject
     * @var RadarContract
     */
    protected $radarService;

    /**
     * @Inject
     * @var RadarRecordContract
     */
    protected $radarRecordService;

    /**
     * @Inject
     * @var WorkContactContract
     */
    protected $workContactService;

    /**
     * @Inject
     * @var RadarChannelContract
     */
    protected $radarChannelService;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployeeService;

    /**
     * @Inject
     * @var RadarChannelLinkContract
     */
    protected $radarChannelLinkService;

    /**
     * @Inject
     * @var CorpContract
     */
    protected $corpService;

    /**
     * @Inject
     * @var WorkContactEmployeeContract
     */
    protected $workContactEmployeeService;

    /**
     * @Inject
     * @var MessageRemind
     */
    protected $messageRemind;

    /**
     * @Inject
     * @var WorkAgentContract
     */
    private $workAgentService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @RequestMapping(path="/operation/radar/readCallback", methods="post")
     * @return array 返回数组
     * @throws \JsonException
     */
    public function handle(): array
    {
        // 参数验证
        $this->validated($this->request->all());
        // 接收参数
        $params = [
            'nickname' => $this->request->input('nickname'),
            'radarId' => (int) $this->request->input('radarId'),
            'linkId' => (int) $this->request->input('linkId'),
            'employeeId' => (int) $this->request->input('employeeId'),
            'clickId' => (int) $this->request->input('clickId'),
            'readTime' => $this->request->input('readTime'),
            'finishRate' => $this->request->input('finishRate'),
        ];

        // 数据统计
        return $this->handleData($params);
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'nickname' => 'required',
            'radarId' => 'required',
            'linkId' => 'required',
            'employeeId' => 'required',
            'clickId' => 'required',
            'readTime' => 'required',
            'finishRate' => 'required',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'nickname.required' => 'nickname 必传',
            'radarId.required' => 'radarId 必传',
            'linkId.required' => 'linkId 必传',
            'employeeId.required' => 'employeeId 必传',
            'clickId.required' => 'clickId 必传',
            'readTime.required' => 'readTime 必传',
            'finishRate.required' => 'finishRate 必传',
        ];
    }

    /**
     * @param $params
     * @throws \JsonException
     */
    private function handleData($params): array
    {
        // 雷达
        $radar = $this->radarService->getRadarById($params['radarId'], ['type', 'title', 'link', 'pdf', 'article_type', 'article', 'action_notice', 'dynamic_notice', 'tag_status', 'contact_tags', 'employee_card', 'corp_id']);
        // 链接
        $link = $this->radarChannelLinkService->getRadarChannelLinkById($params['linkId'], ['channel_id', 'link', 'employee_id', 'click_num', 'click_person_num']);
        // 渠道
        $channel = $this->radarChannelService->getRadarChannelById($link['channelId'], ['id', 'name', 'corp_id']);

        $params['finishRate'] = round($params['finishRate'], 2);
        // 员工
        $employee = $this->workEmployeeService->getWorkEmployeeById($params['employeeId'], ['name', 'wx_user_id']);
        $content = "【雷达文章】\n「{$params['nickname']}」打开了「{$employee['name']}」在「自建渠道-{$channel['name']}」里发送的互动雷达「{$radar['title']}」，阅读时长为{$params['readTime']}，阅读完成率为{$params['finishRate']}%\n客户昵称:{$params['nickname']}\n客户类型:微信客户\n<a href='{$link['link']}'>点击查看链接</a>";

        // 点击记录添加阅读时长与完成率
        $data = [
            'read_time' => $params['readTime'],
            'finish_rate' => $params['finishRate'],
        ];
        $this->radarRecordService->updateRadarRecordById($params['clickId'], $data);
        // 行为通知
        if ($radar['actionNotice'] === 1) {
            $this->actionNotice($radar['corpId'], $employee['wxUserId'], $content);
        }

        // 动态通知 TODO 需要补充动态通知
        if ($radar['dynamicNotice'] == 1) {
        }

        // 自动打标签 TODO 需要补充动态通知
        if ($radar['tagStatus'] === 1) {
        }
        return [];
    }

    /**
     * @throws \JsonException
     */
    private function actionNotice(int $corpId, string $wxUserId, string $content): void
    {
        $this->messageRemind->sendToEmployee($corpId, $wxUserId, 'text', $content);
    }
}
